import React, { useState, useEffect, useMemo } from 'react';
import s from './style.module.css';
import cn from 'classnames';
import Breadcrumb, { Item } from '../../../components/Breadcrumb';
import Helper from '../../../components/Helper';
import { withRouter } from 'react-router';
import SecurityRating from './SecurityRating';
import { IconS } from './SecurityRating/picture';
import PropTypes from 'prop-types';
import Label from '../../../components/Label';
import Table from '@knownsec/react-component/dist/Table';
import EmptyData from '../../../components/empty/EmptyData';
import fetchFer from 'API/fetch';
import Select from '@knownsec/react-component/dist/Select';
import { datetime, timeChange } from '../../../../common/formatter';
import Tabs, { TabPane } from '@kuiper-components/tabs';
import { turnToUrlparam } from '../../../helpers/getUrlParams';
import Detail from '../../Task/TaskDetail/HostDetail/VulTable/index.jsx';
import { portCol, osCol } from '../../Task/TaskDetail/columns';
import Button from '@kuiper-components/button';
import KDialog from '@knownsec/react-component/dist/Dialog';
import Form from '@knownsec/react-component/dist/Form';
import Icon from '@knownsec/react-component/dist/Icon';
import Message from '@knownsec/react-component/dist/Message';
import KInput from '@knownsec/react-component/dist/Input';
import Tooltip from '@knownsec/react-component/dist/Tooltip';
import Textarea from '@knownsec/react-component/dist/Textarea';

const infoObj = { name: '资产名称', target: '资产地址', status: '响应状态' };
function JobDetail({ assetType, row = {} }) {
	const [detail, setDetail] = useState({});
	const [hostInfo, setHostInfo] = React.useState({});
	const [selVal, setSelVal] = useState([row?.task?.task_id]);
	const [timeOpt, setTimeOpt] = useState([]);
	useMemo(async () => {
		const res = await fetchFer(
			`/api/v2/repodatas/task_completed_times?job_id=${row.job_id}&task_types=hostVul`,
			{
				method: 'GET',
			}
		).catch(() => {
			return [];
		});
		const time = res.data.map(e => {
			const differenceTime = Date.now() - new Date(datetime(e.time)).getTime();
			return {
				label: datetime(e.time) + `（${timeChange(differenceTime)}前）`,
				labelHtml: `<p style="display:flex"><span style="width: 150px;display: inline-block;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;">${datetime(
					e.time
				)}</span>
			<span style="width: 90px;display: inline-block;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;">（${timeChange(
				differenceTime
			)}前）</span></p>`,
				value: e.id,
				type: e.trigger_type,
			};
		});
		setTimeOpt(time);
		setSelVal(time[0] ? [time[0].value] : []);
	}, [assetType]);
	const getHostDetail = async () => {
		const sendData = {
			id: selVal[0],
			job_id: row.job_id,
		};
		const params = turnToUrlparam(sendData);
		const res = await fetchFer(
			`/api/v2/tasks/vul_host/detail/overview?${params}`,
			{
				method: 'GET',
			}
		).catch(error => {
			return null;
		});
		setDetail(res || {});
	};
	const getData = async (num, size) => {
		const sendData = {
			id: selVal[0],
			job_id: row.job_id,
		};
		const params = turnToUrlparam(sendData);
		const host = await fetchFer(
			`/api/v2/tasks/vul_host/detail/host?${params}`,
			{
				method: 'GET',
			}
		).catch(error => {
			return null;
		});
		setHostInfo(host || {});
	};
	const resDemo = e => {
		const aa = e && e.replace(/\d+/g, `<span style='color: #EA0028'>$&</span>`);
		return aa;
	};
	useEffect(() => {
		getData();
		getHostDetail();
	}, [selVal]);
	const changeUrl = () => {
		let type = '';
		timeOpt.forEach(item => {
			if (selVal[0] === item.value) {
				type = item.type;
			}
		});

		if (!row.is_checked) {
			return {
				pathname: '/task/createJob',
				search: `note=${row.note}&target_url=${row.target_url}&jid=${row.job_id}`,
			};
		} else {
			return {
				pathname: `/job-manage/host-task/detail/`,
				search: `jid=${row.job_id}&id=${row.task.asset_task_id}&tid=${selVal}&type=${type}&last=host`,
			};
		}
	};
	const mockData = [
		{
			web_property: '测试',
			name: '测试name',
			is_access: '是',
		},
		{
			web_property: '测试2',
			name: '测试name2',
			is_access: '否',
		},
	];
	const connectCol = [
		{
			title: 'web资产',
			dataIndex: 'web_property',
			key: 'web_property',
			width: 200,
		},
		{
			title: '网站名称',
			dataIndex: 'name',
			key: 'name',
			width: 200,
		},
		{
			title: '是否接入ScanV',
			dataIndex: 'is_access',
			key: 'is_access',
			width: 200,
		},
		{
			title: '操作',
			width: 80,
			render(e, row) {
				console.log(e, row);
				return (
					<>
						{row.is_access === '是' ? (
							<Button link primary>
								查看详情
							</Button>
						) : (
							<Button link primary onClick={() => setCreatWebVisible(true)}>
								接入ScanV
							</Button>
						)}
					</>
				);
			},
		},
	];
	const [creatWebVisible, setCreatWebVisible] = useState(false);
	const [webForm] = Form.useForm();
	const [isCreate, setIsCreate] = useState(true);
	const [webRecord, setWebRecord] = useState(null);
	const [resultWeb, setResultWeb] = useState(null);
	const [resultWebVisible, setResultWebVisible] = useState(false);
	const validatormap = (rule, value) => {
		if (rule.field === 'note') {
			if (!value || !value.trim()) {
				return Promise.reject('请输入资产名称');
			} else if (
				!(
					value.trim().replace(/[a-zA-Z0-9_\u4E00-\u9FA5]{1,50}/g, '')
						.length === 0
				)
			) {
				return Promise.reject(
					'名称格式错误，只能输入1～50个中文、英文字母、数字、下划线'
				);
			} else {
				return Promise.resolve();
			}
			// eslint-disable-next-line prefer-promise-reject-errors
		} else {
			return Promise.resolve();
		}
	};
	const handleCreateJob = async record => {
		if (!isCreate) return false;

		webForm.current.validateFields().then(async res => {
			if (res) {
				setIsCreate(false);
				const url = '/api/v2/asset/asset_add';
				const addData = {
					note: res.note,
					target_url: res.protocol[0] + res.url,
					asset_type: 'web',
					source_ips: res.source_ip.split('\n'),
				};
				const resp = await fetchFer(url, {
					method: 'POST',
					body: JSON.stringify(addData),
					checkStatus: 501,
				});
				setIsCreate(true);
				if (resp?.message?.indexOf('失败') > -1) {
					setResultWeb(resp.data);
					setCreatWebVisible(false);
					setResultWebVisible(true);
				} else {
					if (resp.code === 0) setCreatWebVisible(false);
					Message.show({
						type: resp.code === 0 ? 'success' : 'error',
						message: resp.message || resp.msg,
						onclose() {
							if (resp.code === 0) {
								window.location.href = `/#/asset-manage/manage/web?filter=${encodeURI(
									JSON.stringify({ target_url: webRecord.target_url })
								)}`;
							}
						},
					});
				}
				return resp;
			}
		});
	};

	return (
		<div className={s.content}>
			<div className={s.header}>
				<div className={s.left}>
					<SecurityRating score={detail.score} />
				</div>
				<div className={s.right}>
					{/* {timeOpt.length > 0 && (
						<div className={s.timeType}>
							历史监测报告:
							<Select
								pro
								value={selVal}
								placeholder="检测历史"
								option={timeOpt}
								className={s.sel}
								onChange={({ selectedItem }) => {
									setSelVal([selectedItem[0].value]);
								}}
							/>
						</div>
					)} */}
					<Label className={s.labelDetail}>主机安全监测</Label>
					<div className={cn(s.df, s.aic, s.mb16)}>
						{Object.keys(infoObj)
							.slice(0, 2)
							.map(e => {
								return (
									<p className={cn(s.flex1)} key={e}>
										<span className={s.infoName}>{infoObj[e]}</span>：
										<span className={s.infoVal}>{detail[e]}</span>
									</p>
								);
							})}
					</div>
					<div className={cn(s.df, s.aic, s.mb16)}>
						{Object.keys(infoObj)
							.slice(2, 4)
							.map(e => {
								return (
									<p className={cn(s.flex1)} key={e}>
										<span className={s.infoName}>{infoObj[e]}</span>：
										<span className={s.infoVal}>{detail[e]}</span>
									</p>
								);
							})}
					</div>
					<div className={s.rBox}>
						{/* <Link className={s.seeInfo} to={changeUrl()}>
							{row.is_checked ? '查看监测详情' : '下发监测任务'}
						</Link> */}
						<p className={s.rBoxp1}>
							<span className={s.icon}>
								<IconS />
							</span>
							监测结果
							<Helper
								overlay="同步资产最新一次主机漏洞监测结果。"
								placement="top"
							/>
						</p>
						<p
							dangerouslySetInnerHTML={{ __html: resDemo(detail.result) }}
							className={cn(s.infoVal, s.w100p)}
						></p>
					</div>
				</div>
			</div>
			<div className={s.infoBody}>
				<Tabs className={s.tabs}>
					<TabPane key="4" tab="主机安全">
						<div className={cn(s.mt1r, s.aic)}>
							最近更新时间：
							<span className={cn(s.pl10, s.pr20)}>
								{Object.keys(timeOpt).length === 0
									? '- -'
									: timeOpt[0].label.split('（')[0]}
							</span>
						</div>
						<Detail
							jid={row.job_id}
							checked={row.task.host_vul_task_checked}
							linkType="manage"
							lastTid={selVal[0]}
						/>
					</TabPane>
					<TabPane key="5" tab="信息">
						<>
							<div className={cn(s.mt1r, s.aic)}>
								最近更新时间：
								<span className={cn(s.pl10, s.pr20)}>
									{Object.keys(timeOpt).length === 0
										? '- -'
										: timeOpt[0].label.split('（')[0]}
								</span>
							</div>
							<div className={s.item}>
								<p className={s.itemTitle}>基本信息</p>
								<div className={s.textBox}>
									<p>
										<span>地理位置：</span>
										{hostInfo.base_info?.local || '- -'}
									</p>
									<p className={s.textBoxP2}>
										<span>设备类型：</span> {hostInfo.base_info?.type || '- -'}
									</p>
								</div>
							</div>
							<div className={s.item}>
								<p className={s.itemTitle}>开放端口服务</p>
								<div className={s.tableBox}>
									<Table
										columns={portCol}
										data={hostInfo?.port_infos}
										loading={false}
									/>
								</div>
							</div>
							<div className={s.item}>
								<p className={s.itemTitle}>关联web资产</p>
								<Table
									columns={connectCol}
									// data={hostInfo?.os_info ? [hostInfo?.os_info] : []}
									data={mockData}
									loading={false}
								/>
							</div>
							{/* <div className={s.item}>
						<p className={s.itemTitle}>关联Web服务（2）</p>
						<Table columns={webCol} data={[]} loading={false} />
					</div> */}
						</>
					</TabPane>
				</Tabs>
			</div>
			<KDialog
				visible={resultWebVisible}
				className={s.w700}
				title="提示"
				cancelText={
					resultWeb?.summary?.success ? (
						<span
							onClick={() => {
								window.location.href = `/#/asset-manage/manage/web?filter=${encodeURI(
									JSON.stringify({ target_url: webRecord.target_url })
								)}`;
							}}
						>
							前往Web资产列表
						</span>
					) : (
						'取消'
					)
				}
				onhide={e => {
					setResultWeb(null);
					setResultWebVisible(false);
				}}
				onsubmit={() => setResultWebVisible(false)}
			>
				{resultWeb && (
					<div className={s.p20_0}>
						<div className={s.mb20}>
							共计：{resultWeb?.summary?.total}
							<span className={s.m0_20}>
								成功：{resultWeb?.summary?.success}
							</span>
							失败：{resultWeb?.summary?.fail}
						</div>
						<div className={s.mb10}>添加失败的资产如下：</div>
						<Table
							columns={[
								{
									title: '资产名称',
									key: 'note',
									dataIndex: 'note',
									render(e) {
										return (
											<Tooltip overlay={e} placement="top">
												<span>{e}</span>
											</Tooltip>
										);
									},
								},
								{
									title: '资产地址',
									key: 'target_url',
									dataIndex: 'target_url',
									render(e) {
										return (
											<Tooltip overlay={e} placement="top">
												<span>{e}</span>
											</Tooltip>
										);
									},
								},
								{ title: '源站IP', key: 'source_ip', dataIndex: 'source_ip' },
								{
									title: '失败原因',
									key: 'reason',
									dataIndex: 'reason',
									render(e) {
										return (
											<Tooltip overlay={e} placement="top">
												<span>{e}</span>
											</Tooltip>
										);
									},
								},
							]}
							data={resultWeb?.detail}
						/>
					</div>
				)}
			</KDialog>
			<KDialog
				visible={creatWebVisible}
				className={s.w550}
				title="添加资产"
				onhide={() => {
					setCreatWebVisible(false);
					webForm.current.resetFields();
				}}
				onsubmit={handleCreateJob}
			>
				<div className={cn(s.p20_0, s.createForm)}>
					<Form
						ref={webForm}
						labelCol={{ span: 5 }}
						onValuesChange={(newItem, allValues) => {
							const val = recursion(newItem);
							function recursion(obj) {
								const obj_ = obj;
								const key = Object.keys(obj_);
								if (obj_[key] && typeof obj_[key] === 'object') {
									if ({}.propertyIsEnumerable.call(obj_[key], 'value')) {
										obj_[key] = obj_[key].value;
									} else if (
										{}.propertyIsEnumerable.call(obj_[key], 'selectedItem')
									) {
										if (obj_[key].selectedItem.length > 0) {
											if (obj_[key].selectedItem.length > 1) {
												obj_[key] = obj_[key].selectedItem.map(
													item => item.value
												);
											} else {
												obj_[key] = [obj_[key].selectedItem[0].value];
											}
										} else if (obj_[key].selectedItem.length === 0) {
											obj_[key] = [];
										}
									} else {
										obj_[key] = recursion(obj_[key]);
									}
								}
								return obj_;
							}
							webForm.current.setFieldsValue(val);
						}}
						wrapperCol={{ span: 18 }}
						initialValues={{ remember: true }}
					>
						<Form.Item
							label="资产名称"
							name="note"
							rules={[{ required: true, validator: validatormap }]}
						>
							<KInput placeholder="请输入资产名称" />
						</Form.Item>
						<Form.Item
							label="资产地址"
							name="url"
							rules={[{ required: true, message: '请输入资产地址' }]}
						>
							<div className={cn(s.df, s.aic, s.bdt, 'error-box')}>
								<Form.Item noStyle name="protocol">
									<Select
										className={cn(s.w80, s.appendSelect)}
										option={[
											{ label: 'http://', value: 'http://' },
											{ label: 'https://', value: 'https://' },
										]}
									/>
								</Form.Item>
								<Form.Item noStyle name="url">
									<KInput className={s.flex1} placeholder="请输入资产地址" />
								</Form.Item>
								<Tooltip
									overlay={
										<div>
											协议+子域名/IPv4/IPv6+端口
											<br />
											示例：http://www.example.com:80
											<br />
											<span className="_tipSpan_7z5aq_29">
												http://[AD80:0000:0000:0000:ABAA:0000:00C2:0002]
											</span>
											<br />
											<span className="_tipSpan_7z5aq_29">https://1.1.1.1</span>
											<br />
										</div>
									}
									placement="top"
									children={
										<Icon
											type="question"
											// className={cn(s.cp, s.pa, s.r_20, s.fs20)}
										/>
									}
								></Tooltip>
							</div>
						</Form.Item>
						<Form.Item
							label="源站IP"
							name="source_ip"
							validateStatus="warning"
							help="注：资产认证后，系统默认一周一次监测频率探测资产信息。"
						>
							<Textarea
								rows={4}
								placeholder="请输入源站 IP 地址，若有多个 IP 地址可换行添加，多个源站 IP 算多个资产数量。"
							/>
						</Form.Item>
					</Form>
				</div>
			</KDialog>
		</div>
	);
}
JobDetail.propTypes = {
	assetType: PropTypes.any,
	row: PropTypes.any,
};
export default JobDetail;
